package org.goodsence.frammework.common.utils;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @Author zty
 * @Version 1.0.0
 * @Date 2023 02 16 09 12
 **/
public final class ResultUtils {
    /**
     * 不允许创建对象
     */
    private ResultUtils() {
    }

    /**
     * 成功处理请求
     * @return 200
     */
    public static <T> ResponseEntity<T> ok(){
        return ok(null);
    }

    /**
     * 成功处理请求
     * @param data 响应数据
     * @param <T>
     * @return 200
     */
    public static <T> ResponseEntity<T> ok(T data){
        return ResponseEntity.ok(data);
    }

    /**
     * 201 已创建
     * @param uri 创建的资源地址
     * @return  201
     */
    public static <T> ResponseEntity<T> created(String uri) {
        try{
            return ResponseEntity.created(new URI(uri)).build();
        }catch (URISyntaxException e){
            return noContent();
        }
    }

    /**
     * 已接受请求, 且没有内容响应.
     * @return 204
     */
    public static <T> ResponseEntity<T> noContent(){
        return ResponseEntity.noContent().build();
    }

    /**
     * 客户端错误
     * @param msg 错误原因
     * @return 400
     */
    public static <T> ResponseEntity<T> badRequest(T msg) {
        return ResponseEntity.badRequest().body(msg);
    }

    /**
     * 401
     * @param <T>
     * @return
     */
    public static <T> ResponseEntity<T> unAuthorized() {
        return status(HttpStatus.UNAUTHORIZED);
    }

    /**
     * 403
     * @return
     */
    public static <T> ResponseEntity<T> forbidden(){
        return status(HttpStatus.FORBIDDEN);
    }

    /**
     * 服务器错误
     * @return 500
     */
    public static <T> ResponseEntity<T> error(){
        return ResponseEntity.internalServerError().build();
    }

    private static <T> ResponseEntity<T> status(HttpStatus status) {
        return ResponseEntity.status(status).build();
    }

}
